<!-- pay 支付-->
<template>
  <view class="payPage m-order-dialog" id="payPage">
    <view class="pay-page__mask" v-if="isOnePay && markVisible"></view>
    <view class="overflow-auto p-content">
      <view class="payList-box">
        <pay-list
          @payType="getPayType"
          :query="query"
          ref="payList"
          v-model="query.orderType"
          :order-type="query.orderType"
          :list="list"
        />
      </view>
    </view>
  </view>
</template>

<script>
  import { locPreOrderInfo } from '@/utils/locStore/data'
  import PayList from '@/pagesOrder/components/PayList/index'

  import judgePay from '@/mixins/judgePay'
  import umMixin from './mixin/um'
  // #ifdef H5
  import * as wxSdk from '@/utils/sdk/src/wx.js'
  // #endif

  const BALANCE = 'balance' // 余额
  const INTEGRAL = 'integral' // 积分
  export default {
    name: 'pay',
    components: { PayList },
    mixins: [judgePay, umMixin],
    data() {
      return {
        list: [],
        BALANCE,
        INTEGRAL,
        show: false,
        query: {},
        check: [], // balance integral
        route: null,
        fromPath: '', // 从哪个路由进来
        needPay: 0, // 原价
        fromOtherUrl: '',
        preInfo: {
          film: {},
          goods: {}
        }, // 影片订单 信息

        canBack: false,
        isOnePay: true, // 是否只有一种支付,
        markVisible: true,
        msgTest: null,
        fromPathArr: [
          'pages/mine/index',
          'pagesOrder/chooseSet/index',
          'pagesOrder/sureOrder/index'
        ]
      }
    },
    computed: {
      // 影片过来
      isFilm() {
        return this.fromPathArr.includes(this.fromPath)
      },

      isGoods() {
        return this.fromPath === '/snackOrder'
      },
      ticketPriceUnit() {
        return this.$auth.getLocBaseSet().ticketPriceUnit || '元'
      },
      isMall() {
        return (
          this.fromPath === 'pagesOrder/goodsPay/index' ||
          this.query.orderType === 'mall'
        )
      },
      isFood() {
        return this.query.orderType === 'food'
      },
      isCard() {
        return this.query.orderType === 'card'
      },

      totalMoney() {
        const needPay = this.needPay
        const money = needPay
        return this.$utils.toFixed(money)
      }
    },
    onLoad(options) {
      this.query = options
      this.init()
    },

    methods: {
      // 初始化方法
      init() {
        this.ttPay = false
        this.route = this.$tools.getCurrentPage()
        this.setOwnPayList()
        this.initData()
      },

      // 取消卖品订单
      async handleCancelOrder() {
        await this.$utils.sleep(100)
        // const msg = {
        //   title: '温馨提示',
        //   message: '后退将会取消订单，是否取消？',
        //   cancelButtonText: '取消订单',
        //   confirmButtonText: '继续支付'
        // getContainer: () => {
        // return document.getElementById('payPage')
        // }
        // }
        return new Promise((resolve, reject) => {
          const orderId = this.query.mallOrderId
          this.$msg
            .showModal({
              title: '温馨提示',
              content: '后退将会取消订单，是否取消？',
              cancelText: '取消订单',
              confirmText: '继续支付'
            })
            .then(() => {
              this.markVisible = false
              reject()
            })
            .catch((res) => {
              const d = { orderId: orderId }
              this.$msg.loading()
              uni.$api.mall
                .cancelMallOrder(d)
                .then((res) => {
                  this.$msg.hideLoading()
                  resolve()
                })
                .catch(() => {
                  this.canBack = true
                  reject()
                })
            })
        })
      },

      initData() {
        this.fromPath = this.route.fromPath
        // window.location.href.includes('hasPay=1')
        if (this.query.hasPay == 1) {
          this.goPaying()
          return
        }
        // this.query = this.$route.query
        this.needPay = this.$utils.isNaNStr(this.query.needPay)
        this.createdShowDetailInfo()
        this.hasNoPay()
      },

      // 卡 券抵扣完 直接跳出票页
      hasNoPay() {
        const money = this.$utils.isNaNStr(this.totalMoney)
        console.log('hasNoPay', money)
        if (money === 0) {
          this.goPay()
        } else {
          this.getPayWay()
        }
      },
      getPayWay() {
        const query = this.query
        const data = {
          orderType: query.orderType,
          // activityId: this.activityId,
          zoneId: query.zoneId,
          cinemaId: query.cinemaId
        }
        uni.$api.mall.getPayWay(data).then((res) => {
          this.list = res
          if (this.list.length === 1) {
            console.log('this.payType', this.list)
            this.payType = this.list[0].type
            this.$nextTick(() => {
              // 只有一种支付方式
              this.handleHasOnePay()
            })
          } else {
            this.hasMorePay()
          }
        })
      },
      // 生成展示总价详情数据
      createdShowDetailInfo() {
        // const preOrderInfo = auth.sLoc.get('preOrderInfo', {})
        const preOrderInfo = locPreOrderInfo.get()
        this.preInfo = preOrderInfo
        return preOrderInfo
      },

      showBefore() {
        this.umShowBefore()
        this.createdShowDetailInfo()
      },

      // 影片预下单
      createdPrePayDate() {
        const preInfo = this.createdShowDetailInfo()
        const film = preInfo.film || {}
        const juying = film.juying || {}
        const cardInfo = film.cardInfo || {}
        const coupons = film.coupons || []
        const couponIds = coupons
          .map((i) => i.couponId)
          .filter((i) => i)
          .join(',')
        let status = ''

        coupons.forEach((item) => {
          if (item.grouponType === '1') {
            if (item.douyinStatus === '0') {
              status = '0'
            }
          } else {
            if (item.grouponUse === '0') {
              status = '0'
            }
          }
        })

        const douyinStatus = status
        const query = this.query
        const data = {
          orderId: query.filmOrderId,
          cardId: query.cardId,
          lockMobile: query.lockMobile,
          couponIds,
          douyinStatus,
          prePrice: this.totalMoney + '', // 前端预算剩余支付款项
          cardInfo: JSON.stringify(cardInfo), // 使用卡
          goodsOrderId: query.goodsOrderId, // 卖品订单ID
          goodsCouponIds: query.goodsCouponIds, // 卖品订单ID
          jyInfo: JSON.stringify({ cardCode: juying.cardCode }),
          realNameIds: query.realNameIds,
          discountRuleId: query.discountRuleId,
          discountCommodityId: query.discountCommodityId,
          discountCommodityNum: query.discountCommodityNum
        }

        return data
      },

      goPay() {
        this.createPrePay()
      },

      createPrePay() {
        if (this.isFilm) {
          // 影片支付
          const data = this.createdPrePayDate()
          // this.efzMaiEvent()

          this.orderFilmPerPay(data)
        } else if (this.isGoods) {
          this.orderGoodsPerPay()
        } else if (this.isMall) {
          this.orderMallPerPay()
        } else if (this.isFood) {
          this.orderFoodPerPay()
        } else if (this.isCard) {
          this.orderCardPerPay()
        }
      },
      // 充值卡订单预支付
      orderCardPerPay() {
        const query = this.query
        const data = {
          orderId: query.cardOrderId,
          money: query.needPay + '' // 前端预算剩余支付款项
        }
        this.$msg.loading()
        uni.$api.memberCard.confirmPay(data).then((res) => {
          const payPrice = this.$utils.isNaNStr(res.payPrice)
          this.$msg.hideLoading()
          if (payPrice > 0) {
            // 唤起支付
            console.log('唤起支付')
            this.createOrderPay({
              orderId: res.orderId,
              payMoney: res.payPrice
            })
          } else {
            // 不需要支付多余的钱
            this.goPaying()
          }
        })
      },
      // 点餐订单预支付
      orderFoodPerPay() {
        const query = this.query
        const data = {
          orderId: query.foodOrderId,
          cardId: query.cardId,
          money: query.needPay + '' // 前端预算剩余支付款项
        }
        this.$msg.loading()
        uni.$api.orderFood.confirmPay(data).then((res) => {
          const d = res
          const payPrice = this.$utils.isNaNStr(d.payPrice)
          this.$msg.hideLoading()
          if (payPrice > 0) {
            // 唤起支付
            console.log('唤起支付')
            this.createOrderPay({
              orderId: d.orderId,
              payMoney: d.payPrice
            })
          } else {
            // 不需要支付多余的钱
            console.log('不需要支付多余的钱')
            this.goPaying()
          }
        })
      },
      // 商品订单预支付
      orderMallPerPay() {
        const query = this.query
        const locPerInfo = locPreOrderInfo.get()
        // const locPerInfo = auth.sLoc.get('preOrderInfo', {})

        const data = {
          orderId: query.mallOrderId,
          couponId: locPerInfo.couponId,
          cardId: locPerInfo.cardId,
          money: this.totalMoney + '' // 前端预算剩余支付款项
        }
        this.$msg.loading()
        uni.$api.mall.comfirmPay(data).then((res) => {
          const d = res
          const payPrice = this.$utils.isNaNStr(d.payPrice)
          this.$msg.hideLoading()
          if (payPrice > 0) {
            // 唤起支付
            console.log('唤起支付')
            this.createOrderPay({
              orderId: d.orderId,
              payMoney: d.payPrice
            })
          } else {
            // 不需要支付多余的钱
            console.log('不需要支付多余的钱')
            this.goPaying()
          }
        })
      },

      // 卖品订单预支付
      orderGoodsPerPay() {
        const data = {
          orderId: this.query.goodsOrderId,
          prePrice: this.totalMoney + '', // 前端预算剩余支付款项
          lockMobile: this.query.mobile,
          goodsCouponIds: this.query.couponIds || ''
        }
        this.$msg.loading()
        uni.$api.mall.prePay(data).then((res) => {
          const d = res
          const payPrice = this.$utils.isNaNStr(d.payPrice)
          this.$msg.hideLoading()
          if (payPrice > 0) {
            // 唤起支付
            this.createOrderPay({
              orderId: d.orderId,
              payMoney: d.payPrice
            })
          } else {
            // 不需要支付多余的钱
            this.goPaying()
          }
        })
      },

      // 影票订单预支付
      orderFilmPerPay(data) {
        console.log('orderFilmPerPaydata', data)
        this.$msg.loading()
        return uni.$api.orderFilm
          .prePay(data)
          .then((res) => {
            const d = res
            const payPrice = this.$utils.isNaNStr(d.payPrice)
            this.$msg.hideLoading()
            if (payPrice > 0) {
              // 唤起支付
              this.createOrderPay({
                orderId: d.orderId,
                payMoney: d.payPrice
              })
            } else {
              // 不需要支付多余的钱
              this.goPaying()
            }
          })
          .catch(() => {
            this.markVisible = false
          })
      },
      getPayType(type) {
        console.log('getPayType', type)
        this.payType = type
      },

      // 去等待出票页
      goPaying() {
        console.log('支付成功跳转去出票页面')
        const query = {}
        const rQuery = this.query
        if (this.isFilm || rQuery.filmOrderId) {
          query.filmOrderId = rQuery.filmOrderId || ''
        } else if (this.isGoods || rQuery.goodsOrderId) {
          query.goodsOrderId = rQuery.goodsOrderId || ''
        } else if (this.isMall || rQuery.mallOrderId) {
          query.mallOrderId = rQuery.mallOrderId || ''
        } else if (this.isFood || rQuery.foodOrderId) {
          query.foodOrderId = rQuery.foodOrderId || ''
        } else if (this.isCard || rQuery.cardOrderId) {
          query.cardOrderId = rQuery.cardOrderId || ''
        }
        this.$tools.navigateTo('/pagesOrder/paying/index', query, 'reLaunch')
      },

      // 只有一种支付&不支持余额、积分支付 直接唤起支付
      handleHasOnePay() {
        console.log('handleHasOnePay')
        const flag = this.hasOwnPay('Balance', 'Integral')
        if (!flag) {
          this.isOnePay = true
          //  this.goPay()
          const fromOtherUrl = this.route.fromPath === '/' ? '1' : '0'
          // const { fromOtherUrl } = this.$route.meta
          if (fromOtherUrl === '1') {
            // this.$router.go(-1)
            uni.setStorageSync('payIndex', '1')
            this.$tools.navigateTo(-1)
          } else {
            this.goPay()
          }
        } else {
          this.isOnePay = false
        }
      },

      hasMorePay() {
        this.isOnePay = false
      },

      // 获取支付参数
      createOrderPay(query = {}) {
        // #ifdef MP-ALIPAY
        // console.log('checkBeforeAddOrder', my.canIUse('checkBeforeAddOrder'))
        // if (my.canIUse('checkBeforeAddOrder') && this.isMall) {
        //   if (!this.sourceId) {
        //     my.checkBeforeAddOrder({
        //       success: ({ requireOrder, sceneId, sourceId }) => {
        //         console.log(
        //           'checkBeforeAddOrder success',
        //           requireOrder,
        //           sceneId,
        //           sourceId
        //         )
        //         // 基础库 2.8.13 开始支持 sourceId 和 sceneId
        //         // if (requireOrder === 1) {
        //         //   // success 为异步回调，请在回调里完成创建订单操作（注意执行顺序，避免在回调执行前进行订单创建），否则有可能造成结果未返回导致使用条件判断错误
        //         //   this.sourceId = sourceId
        //         // }

        //         if (sourceId) {
        //           this.sourceId = sourceId
        //           this.createOrderPay(query)
        //         } else {
        //           console.log('支付宝版本过低请升级支付宝')
        //         }
        //       },
        //       fail: ({ error, errorMessage }) => {
        //         console.log('errorMessage', error, errorMessage)
        //         this.$msg.toast('服务异常请重试')
        //         this.$tools.navigateTo(-1)
        //       },
        //       complete: () => {}
        //     })
        //     return
        //   }
        // }
        // #endif
        let tradeType = 'JSAPI'
        if (
          this.$auth.platform() === 'mp-alipay' ||
          this.$auth.platform() === 'mp-toutiao'
        ) {
          tradeType = 'xcx'
        } else if (this.$auth.platform() === 'mp-weixin') {
          tradeType = 'JSAPI'
        }
        console.log('this.payType', this.payType)
        let data = {
          payType: this.payType,
          orderType: this.query.orderType,
          tradeType: tradeType,
          orderId: '', // 订单id   *
          payMoney: '' // 需要支付的钱 *
        }
        // #ifdef MP-ALIPAY
        // if (this.sourceId) {
        //   data.sourceId = this.sourceId
        // }
        // #endif
        query = this.$utils.deep(query)
        data = { ...data, ...query }
        uni.$api.pay.createOrderPay(data).then((res) => {
          const resData = res
          this.handlePay(resData)
        })
      },

      handlePay(data) {
        console.log('paydata', data)
        // #ifdef MP-ALIPAY
        // 处理支付
        const aliData = data.alipay
        uni.requestPayment({
          orderInfo: aliData.trade_no,
          success: (res) => {
            if (res.resultCode === '6001') {
              this.$msg.toast('取消支付')
              const fromPath = this.$tools.getCurrentPage().fromPath
              if (fromPath === 'pagesOrder/sureOrder/index') {
                uni.setStorageSync('payIndex', '1')
                this.$tools.navigateTo(-1)
              } else if (fromPath === 'pagesOrder/goodsPay/index') {
                console.log('取消支付')
                this.$tools.navigateTo(
                  '/pagesOrder/order/detail',
                  {
                    orderId: data.orderId,
                    type: this.query.orderType
                  },
                  'redirectTo'
                )
              } else if (fromPath === 'pagesOrder/order/detail') {
                this.$tools.navigateTo(-1)
              } else {
                this.$tools.navigateTo('/pagesOrder/order/detail', {
                  orderId: data.orderId,
                  type: this.query.orderType
                })
              }
            } else if (res.resultCode === '9000' || res.resultCode === '8000') {
              // 支付成功跳转
              console.log(res, 'res')
              this.goPaying()
            } else {
              this.$msg.toast('支付失败', res)
              this.$tools.navigateTo('/pagesOrder/payError/index')
            }
          },
          fail: (err) => {
            this.$msg.toast('支付失败', err)
            this.$tools.navigateTo('/pagesOrder/payError/index')
            // this.$tools.navigateTo(-1)
          }
        })
        // #endif

        // #ifdef MP-WEIXIN
        // 处理支付
        const wxData = data.weixinpay
        if (
          data.payType === 'dceppay' &&
          data.payload.payload &&
          data.payload.payload.appid
        ) {
          //小程序跳转
          uni.navigateToMiniProgram({
            appId: data.payload.payload.appid,
            path: data.payload.payload.path, //time的值为当前时间的time值
            extraData: {
              URL: encodeURI(data.payload.action) //包含接口参数的全链接
            },
            envVersion: data.payload.payload.envVersion, //develop开发版、trial体验版、release正式版
            success: (res) => {
              // 支付成功跳转
              console.log(res, 'res')
              this.$msg.toast('支付成功')
              this.goPaying()
            },
            fail: (err) => {
              console.log(err, 'err')
            }
          })
        } else if (
          data.payload &&
          (data.payload.method === 'POST' ||
            data.payload.method === 'REDIRECT') &&
          data.payload.action
        ) {
          if (
            data.payload.payload.length ||
            Object.keys(data.payload.payload).length
          ) {
            const payload = JSON.stringify(data.payload.payload)
            const url = `https://tkzc-release-cwap.zmaxfilm.com/webview.html?param=${payload}&action=${data.payload.action}&method=${data.payload.method}`
            this.$tools.navigateTo('/pages/webview/webview', { url })
          } else {
            this.$tools.navigateTo('/pages/webview/webview', {
              url: data.payload.action
            })
          }
        } else {
          uni.requestPayment({
            timeStamp: wxData.timeStamp,
            nonceStr: wxData.nonceStr,
            package: wxData.package,
            signType: wxData.signType,
            paySign: wxData.paySign,
            success: (res) => {
              // 支付成功跳转
              console.log(res, 'res')
              this.$msg.toast('支付成功')
              this.goPaying()
            },
            fail: (err) => {
              if (err.errMsg.indexOf('cancel') === -1) {
                this.$msg.toast('支付失败')
                this.$tools.navigateTo('/pagesOrder/payError/index')
              } else {
                this.$msg.toast('取消支付')
                const fromPath = this.$tools.getCurrentPage().fromPath
                if (fromPath === 'pagesOrder/sureOrder/index') {
                  uni.setStorageSync('payIndex', '1')
                  this.$tools.navigateTo(-1)
                  // this.$tools.navigateTo('/pages/index/index', {}, 'switchTab')
                } else if (fromPath === 'pagesOrder/goodsPay/index') {
                  console.log('取消支付')
                  this.$tools.navigateTo(
                    '/pagesOrder/order/detail',
                    {
                      orderId: data.orderId,
                      type: this.query.orderType
                    },
                    'redirectTo'
                  )
                } else if (
                  fromPath === 'pagesOrder/order/detail' ||
                  fromPath === 'pagesOrder/card/recharge'
                ) {
                  this.$tools.navigateTo(-1)
                } else {
                  this.$tools.navigateTo('/pagesOrder/order/detail', {
                    orderId: data.orderId,
                    type: this.query.orderType
                  })
                }

                // this.$tools.navigateTo(-1)
              }
            }
          })
        }
        // #endif
        // #ifdef H5
        this.h5Pay(data)
          .then(() => {
            this.$msg.toast('支付成功')
            this.goPaying()
          })
          .catch((err) => {
            console.log('err', err)
            if (!(typeof err === 'object' && err.myMsg)) {
              // this.isOnePay && this.$router.go(-1)
              uni.setStorageSync('payIndex', '1')
              // #ifdef MP-WEIXIN || MP-ALIPAY || MP-TOUTIAO
              this.isOnePay && this.$tools.navigateTo(-1)
              // #endif
              // #ifdef H5
              if (this.isOnePay) {
                if (this.route.fromPath !== 'pagesOrder/goodsPay/index') {
                  this.$tools.navigateTo(-1)
                } else {
                  this.$tools.navigateTo(
                    '/pagesOrder/order/detail',
                    {
                      orderId: data.orderId,
                      type: this.query.orderType
                    },
                    'redirectTo'
                  )
                }
              }
              // #endif
            }
          })
        // #endif
      },
      h5Pay(data) {
        const payType = data.payType
        const type = data.type
        const d = data.payload
        if (type === 'form') {
          // 网关支付
          if (d.method.toLocaleLowerCase() === 'redirect') {
            setTimeout(() => {
              window.location.href = d.action
            }, 200)
            return Promise.reject({ msg: '进行网关支付' })
          }
          this.$utils.submitForm(d.action, d.method, d.payload)
        } else if (type === 'sdk') {
          if (payType === 'weixinpay') {
            return wxSdk.wxPay(d)
          }
        }
      }
    }
  }
</script>
<style lang="scss" scoped>
  .payList-box {
    background: #fff;
    padding-left: 0.3rem;
    padding-right: 0.3rem;
    box-sizing: border-box;
  }

  .icon-question {
    font-size: 0.32rem;
    margin-left: 0.1rem;
    color: $gray;
  }

  .payPage {
    position: relative;
    height: 100%;
    width: 100%;
    padding-bottom: 1.82rem;
    box-sizing: border-box;

    .btn-box {
      width: 100%;
      position: absolute;
      bottom: 0;
      background: #fff;
    }
  }

  .p-content {
    height: 100%;
    // overflow-x: hidden;
  }
  .footer {
    position: absolute;
    bottom: 0;
    width: 100%;
    right: 0;
    left: 0;
    // margin-bottom: 0.2rem;
    .OrderFooterBtn {
      width: 100%;
    }
  }
  .pay-page__mask {
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    right: 0;
    background: $bgColor;
    z-index: 2206;
  }
</style>
